package kr.co.skplanet.commute.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;

import kr.co.skplanet.commute.domain.SecurityUser;
import kr.co.skplanet.commute.domain.User;
import kr.co.skplanet.commute.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service( value="securityUserService" )
public class SecurityUserSeviceImpl implements SecurityUserService {

	@Autowired
	private UserService userService;

	@Autowired
	private MessageSource messageSource;
	
	@Override
	@Transactional( readOnly = true )
	public AbstractSecurityUser loadUserByUsername( String username ) throws UsernameNotFoundException, DataAccessException {

		User user = userService.getUserFromEmail( username );
		if(user == null) {
			throw new UsernameNotFoundException(messageSource.getMessage("error.login.exist", new String[]{ "존재하지 않는 사용자 아이디입니다."}, Locale.getDefault()));			
		}
		
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		

		authorities = new ArrayList<GrantedAuthority>();
		authorities.add(new SimpleGrantedAuthority(user.getAuthority()));

		SecurityUser securityUser =  new SecurityUser( user.getEmail(), user.getPassword(), user.getSalt(), true, true, true, true, authorities );
		securityUser.setUserId( user.getId() +"" );
		securityUser.setEmail( user.getEmail() );
		securityUser.setName( user.getName() );
		securityUser.setNickname( user.getNickname() );

		return securityUser;
	}

}
